import React, { useRef } from "react";
import { useEffect } from "react";
import Sign3DManager from "./utils/Sign3DManager";
import useData from "@/hooks/useData";
import { Settings } from "lucide-react";
import { Link } from "react-router-dom";
import useUsers from "@/hooks/useUsers";
import { initMqtt } from "./utils/initMqtt";

const Preview = () => {
  const { config } = useData();
  const ref = useRef(null);
  const sign3dRef = useRef(null);
  const users = useUsers();
  const mqttDestoryRef = useRef(null);

  useEffect(() => {
    const destroy = () => {
      sign3dRef.current?.destroy();
      sign3dRef.current = null;
    };

    if (!config) {
      return destroy;
    }

    if (users.length === 0) {
      return destroy;
    }

    sign3dRef.current = new Sign3DManager(ref.current, config, users);
    initMqtt((_, payload) => {
      sign3dRef.current?.addUser({
        id: payload,
        avatar: payload,
      });
    }).then((mqttDestory) => {
      mqttDestoryRef.current = mqttDestory;
    });

    return () => {
      destroy();
      mqttDestoryRef.current?.();
    };
  }, [config, users]);

  return (
    <>
      {users.length === 0 && (
        <div className="text-3xl font-bold text-center absolute top-0 bottom-0 left-0 right-0 flex justify-center items-center">
          暂无签到用户
        </div>
      )}
      <div
        className="flex flex-col items-center justify-center h-screen bg-gray-100"
        ref={ref}
      />
      <Link to={"/edit"} className="fixed right-2 top-2 z-10 group">
        <Settings className="text-white invisible group-hover:visible" />
      </Link>
    </>
  );
};

export default Preview;
